// axios统一的配置
import axios from "axios"
import qs from 'qs'
// import { useRouter } from "vue-router";
import router from "@/router"
// const router = useRouter();

const baseurl = "/api/"
import { ElMessage } from 'element-plus'


// 请求拦截器
axios.interceptors.request.use((req: any) => {
    // 请求头
    if (sessionStorage.getItem("userinfo")) {
        req.headers.authorization = JSON.parse(sessionStorage.getItem("userinfo") || "").token
    }
    return req
})

// 响应拦截器
axios.interceptors.response.use((res: any) => {
    // 过期提示
    if (res.data.code == 403) {
        ElMessage.warning(res.data.msg)
        // 跳转到登录页
        router.push({
            path: "/login"
        })
    }
    return res.data
})
// get 
export const get = (url: string, params = {}) => {
    return axios.get(baseurl + url, { params })
}
// post
export const post = (url: string, params: any = {}, isfile = false) => {
    // 参数序列化
    let data;
    if (isfile) {
        data = new FormData()
        for (let key in params) {
            data.append(key, params[key])
        }
    } else {
        data = qs.stringify(params)
    }
    return axios.post(baseurl + url, data)
}